<?php

namespace Theatre;

class Session  {
	/**
	 * The model for this session
	 */
	protected $model;


	/**
	 * The save path for this session;
	 */
	protected $savePath;


	/**
	 * The session name
	 */
	protected $sessionName;


	/**
	 * Constructor
	 *
	 * @param $model
	 */
	public function __construct($model, $sessionKey) {
		$this->model = $model;

		register_shutdown_function('session_write_close');

		ini_set('session.use_trans_sid', 0);
		ini_set('url_rewriter.tags', '');
		ini_set('session.save_handler', 'user');
		ini_set('session.serialize_handler', 'php');
		ini_set('session.use_cookies', 1);
		ini_set('session.name', $sessionKey);
		ini_set('session.cookie_lifetime', 0);
		ini_set('session.cookie_path', '/');
		ini_set('session.auto_start', 0);

		session_set_save_handler(
			array($this, 'open'),
			array($this, 'close'),
			array($this, 'read'),
			array($this, 'write'),
			array($this, 'destroy'),
			array($this, 'gc')
		);

		session_start();
	}


	/**
	 * Open the session
	 *
	 * @param $savePath
	 * @param $sessionName
	 */
	public function open($savePath, $sessionName) {
		$this->savePath    = $savePath;
		$this->sessionName = $sessionName;

		return true;
	}


	/**
	 * Close the session
	 */
	public function close() {
		return true;
	}


	/**
	 * Read a specified session
	 *
	 * @param $id
	 */
	public function read($id) {
		$row = $this->model->dbRun('getSessionById($1)', $id);

		return empty($row) ? false : $row->data;
	}


	/**
	 * Write the session
	 *
	 * @param $id
	 * @param $data
	 */
	public function write($id, $data) {
		if (!$id) {
			return false;
		}

		$this->model->dbRun('createSession($1, $2, $3)', $id, $data, time() + (60 * 60 * 3));

		return true;
	}


	/**
	 * Destroy the specified session
	 *
	 * @param $id
	 */
	public function destroy($id) {
		$this->model->dbRun('deleteSessionById($1)', $id);

		return true;
	}


	/**
	 * Garbage collection for the session
	 *
	 * @param $maxlifetime
	 */
	public function gc($maxlifetime = null) {
		if (!$maxlifetime) {
			$maxlifetime = time();
		}

		$this->model->dbRun('deleteExpiredSession($1)', $maxlifetime);

		return true;
	}


	/**
	 * Reset/regenerate the session ID
	 *
	 */
	public function resetSessionId() {
		$old = session_id();
		session_regenerate_id();
		$new = session_id();

		$this->model->dbRun('resetSession($1, $2)', $new, $old);
	}
}
